﻿using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Newtonsoft.Json;
using WorkflowCore.Interface;
using WorkflowCore2210A.Application;
using WorkflowCore2210A.Application.Dto;
using WorkflowCore2210A.Application.Dto.Input;
using WorkflowCore2210A.Application.Dto.Output;

namespace WorkflowCore2210A.Host.Controllers
{
    /// <summary>
    /// 流程管理
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class WorkflowController : ControllerBase
    {
        private readonly IWorkflowService _workflowService;
        private readonly IWorkflowHost _workflowHost;
        //private readonly IUserService _userService;

        public WorkflowController(IWorkflowService workflowService,
            IWorkflowHost workflowHost
            )
        {
            _workflowService = workflowService;
            _workflowHost = workflowHost;
            
        }

        /// <summary>
        /// 添加流程定义
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult<int> AddWorkflowDefinition(WorkflowDefinitionInput input)
        {
            _workflowService.AddWorkflowDefinition(input);
            return new ApiResult<int>()
            {
                Code = Application.Enums.StatueCode.Ok,
                Data = 1,
                Message ="添加流程定义成功"
            };
        }

        /// <summary>
        /// 流程发起
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> StartWorkflow(WorkflowStartInput input)
        {
            var workflowData = JsonConvert.DeserializeObject<Dictionary<string, object>>
                                (JsonConvert.SerializeObject(input));

            var workflowId = await _workflowHost.StartWorkflow(input.WorkflowDefinitionId, input.Version, workflowData);

            // 添加流程业务实例
            _workflowService.AddWorkflowInstance(new()
            {
                ApplicantUserName = input.UserName,
                DefinitionId = input.WorkflowDefinitionId,
                FormData = input.FormData,
                Title = input.Title,
                WorkflowId = workflowId,
                AuditUserName = string.Empty, // 在AuditStep中进行修改
                StepName = string.Empty
            });

            return new ApiResult<int>()
            {
                Code = Application.Enums.StatueCode.Ok,
                Data = 1,
                Message = $"流程发起成功:{workflowId}"
            };
        }


        /// <summary>
        /// 审批
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public async Task<ApiResult<int>> Audit(AuditInput input)
        {
            // 判断当前审批人是否有审批任务(后面再完善)
            if (!_workflowService.HasAudit(input.WorkflowId,input.AuditUserId))
            {
                return new ApiResult<int>()
                {
                    Code = Application.Enums.StatueCode.Fail,
                    Data = 0,
                    Message = "暂无审批任务"
                };
            }

            // 更新审批状态
            _workflowService.UpdateAudit(new()
            {
                AuditOperation = input.AuditOperation,
                Remark = input.Remark,
                WorkflowId = input.WorkflowId,
                AuditUserId = input.AuditUserId
            });

            // 向流程引擎发送审批指令
            await _workflowHost.PublishEvent("MyEvent", input.WorkflowId, input.Remark);

            return new ApiResult<int>()
            {
                Code = Application.Enums.StatueCode.Ok,
                Data = 1,
                Message = "审批完成"
            };
        }

        /// <summary>
        /// 流程定义分页查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public ApiPaging<WorkflowDefinitionOutput> GetWorkflowDefinitionList([FromQuery]PageInput input)
        {
            return _workflowService.GetWorkflowDefinitionList(input);
        }

        /// <summary>
        /// 流程实例查询
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpGet]
        public ApiPaging<WorkflowInstanceOutput> GetWorkflowInstanceList([FromQuery]QueryWorkflowInstalceInput input)
        {
            return _workflowService.GetWorkflowInstanceList(input);
        }





        /// <summary>
        /// 获取我的待办
        /// </summary>
        /// <returns></returns>
        [HttpGet]
        public ApiPaging<AuditOutput> GetAuditList([FromQuery]PageInput input, long userId)
        {
            return _workflowService.GetAuditList(input,userId);
        }

        /// <summary>
        /// 保存表单模版
        /// </summary>
        /// <param name="input"></param>
        /// <returns></returns>
        [HttpPost]
        public ApiResult<int> SaveFormTemplate(SaveFormTemplateInput input)
        {
            return _workflowService.SaveFormTemplate(input);
        }

        /// <summary>
        /// 获取表单模版  
        /// </summary>
        /// <param name="definitionModelId"></param>
        /// <returns></returns>
        [HttpGet]
        public ApiResult<FormTemplateOutput> GetFormTemplate(long definitionModelId)
        {
            return _workflowService.GetFormTemplate(definitionModelId);
        }

        /// <summary>
        /// 获取流程实例详情
        /// </summary>
        /// <param name="workflowId"></param>
        /// <returns></returns>
        [HttpGet]
        public ApiResult<WorkflowInstalceDetailOutput> GetWorkflowDetail(string workflowId)
        {
            return _workflowService.GetWorkflowDetail(workflowId);
        }
    }
}
